﻿using System.Data;
using System.Transactions;
using GPSTrackingWebsiteManager.ClassManager;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class StockByCategories : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.StockColumn.Name.ToString();
                expression.SetSortOrder("Ascending");
                this.StocksGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        public string GetPathStockCategoriesImage()
        {
            return "../../PointOfSale/CategoryItems/" + getSessionManager().GUID + "/";
        }

        public string GetPathStockCategoriesImage(string imageUrl)
        {
            if (System.IO.File.Exists(Server.MapPath("../../PointOfSale/CategoryItems/" + getSessionManager().GUID + "/" + imageUrl)))
                return "../../PointOfSale/CategoryItems/" + getSessionManager().GUID + "/" + imageUrl;
            else
                return "../../Template/Icons/24px/image-up-icon.png";
        }

        public string GetPathStockImage()
        {
            return "../../PointOfSale/StockItems/" + getSessionManager().GUID + "/";
        }

        public string GetPathStockImageToCreate()
        {
            return "../../PointOfSale/StockItems/" + getSessionManager().GUID;
        }

        public string GetPathStockImage(string imageUrl)        
        {
            if (!string.IsNullOrEmpty(imageUrl))
                return "../../PointOfSale/StockItems/" + getSessionManager().GUID + "/" + imageUrl;
            else
                return string.Empty;
        }

        public string GetImageUrl(string imageUrl)
        {
            return "OpenLightBox('" + imageUrl + "'); return false;";
        }

        public string GetPathStockPdf()
        {
            return "../../PointOfSale/StockPDF/" + getSessionManager().GUID + "/";
        }

        public string GetPathStockPdfToCreate()
        {
            return "../../PointOfSale/StockPDF/" + getSessionManager().GUID;
        }

        public string GetPathStockVideoToCreate()
        {
            return "../../PointOfSale/StockVideos/" + getSessionManager().GUID;
        }

        public string GetPathStockPdf(string pdfUrl)
        {
            return "../../PointOfSale/StockPDF/" + getSessionManager().GUID + "/" + pdfUrl;                       
        }

        public string GetPathStockVideo(string videoUrl)
        {
            return "../../PointOfSale/StockVideos/" + getSessionManager().GUID + "/" + videoUrl;
        }

        public string GetPathStockVideo()
        {
            return "../../PointOfSale/StockVideos/" + getSessionManager().GUID + "/";
        }

        public string GetPDFUrl(string pdf)
        {
            return "OpenLightBoxPDF('" + pdf + "');";
        }

        public string GetVideoUrl(string video)
        {
            return "OpenLightBoxVideo('" + video + "');";
        }

        public bool IsPDFVisible(string pdf)
        {
            return !string.IsNullOrEmpty(pdf);
        }

        public bool IsVideoVisible(string video)
        {
            return !string.IsNullOrEmpty(video);
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            StocksGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in StocksGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            ResizeGrid();
            StocksGrid.MasterTableView.Rebind();
        }

        private void ResizeGrid()
        {
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value);
            decimal Width = Convert.ToDecimal(HiddenFieldWidth.Value) / 4;

            StocksGrid.Height = Unit.Parse(Convert.ToString(Height));
            StocksGrid.Width = Unit.Parse(Convert.ToString(Width * 3));
            StockCategoriesGridTree.Height = Unit.Parse(Convert.ToString(Height));
            StockCategoriesGridTree.Width = Unit.Parse(Convert.ToString(Width * 1));
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            ShowErrorMessage(HiddenFieldError.Value);
        }

        public void ShowErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Productos ...');", true);
        }

        public void ShowInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Productos ...');", true);
        }

        public void ShowWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Warning", "objWindowsMessageManager.show_Warning('" + msg + "','Productos ...');", true);
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void StockCategoriesGridTree_ItemCommand(object sender, GridCommandEventArgs e)
        {
            Telerik.Web.UI.RadTreeView tree;

            switch (e.CommandName)
            {
                case "ExpandAllNodes":
                    tree = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                    tree.ExpandAllNodes();
                    break;

                case "CollapseAllNodes":
                    tree = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                    tree.CollapseAllNodes();
                    break;
            }
            ResizeGrid();
        }

        protected void StockCategoriesGridTree_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            StockCategoriesGridTree.DataSource = new String[] { "Tree" };
        }

        private void BuildStockCategoriesTree(string name )
        {
            Telerik.Web.UI.RadTreeView treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;

            System.Data.DataTable dt = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesProvider.GetAllByCompanyID(getSessionManager().CompanyIDSelectedComboBox, name);

            treeView.DataTextField = "Name";
            treeView.DataValueField = "ImageUrl";
            treeView.DataFieldID = "StockCategoryID";
            treeView.DataFieldParentID = "ParentStockCategoryID";

            treeView.DataSource = dt;
            treeView.DataBind();

        }

        protected void StockCategoriesGridTreeView_NodeDataBound(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
        {
            e.Node.ImageUrl = GetPathStockCategoriesImage((e.Node.DataItem as System.Data.DataRowView)["ImageUrl"].ToString());
            e.Node.Value = (e.Node.DataItem as System.Data.DataRowView)["StockCategoryID"].ToString();
        }
       
        protected void StockCategoriesGridTreeView_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            GetStocksByCategories(int.Parse(e.Node.Value.ToString()));
            StocksGrid.DataBind();
            ResizeGrid();
        }

        protected void setSessionManager(int value)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            objSessionManager.StockByCategories_StocksAditionalImages_StockId = value;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;
        }

        protected void GetStocksByCategories(int? stockCategoryId)
        {

            var FalconSystemProvider = new EntityFrameworkManager.FalconSystemProvider();
            int companyId = getSessionManager().CompanyIDSelectedComboBox;
            
            var stockQuery = FalconSystemProvider.Stocks.Where(x => x.CompanyID == companyId && x.StockCategoryID == stockCategoryId);

            StocksGrid.DataSource = stockQuery.ToList();           
        }

        protected void StockCategoriesGridTree_DataBound(object sender, EventArgs e)
        {
            BuildStockCategoriesTree("-1");
        }

        protected int getStockCategoryIdSelected()
        {
            try
            {
                Telerik.Web.UI.RadTreeView treeView;

                if (StockCategoriesGridTree.Items.Count > 0)
                {
                    treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                    if (treeView.SelectedNode != null)
                        return int.Parse(treeView.SelectedNode.Value);
                }
            }
            catch { }
            return -1;
        }

        protected void StocksGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetStocksByCategories(getStockCategoryIdSelected());
            ResizeGrid();
        }

        protected void StocksGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {

            try
            {
                #region Stock Entity Recollect

                var stockEntity = new EntityFrameworkManager.Stock();
                var stockLogEntity = new EntityFrameworkManager.StockLog();
                var stockCategoryEntity = new EntityFrameworkManager.StockCategory();

                DateTime dateTransaction = DateTime.Now;
                Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
                string typeUserTransaction = "";
                string usernameTransaction = "";
                int companyId = getSessionManager().CompanyIDSelectedComboBox;
                string path;


                //Extract info
                stockEntity.StockCode = (e.Item.FindControl("txtStockCode") as RadTextBox).Text;
                stockEntity.StockBarCode = (e.Item.FindControl("txtBarCode") as RadTextBox).Text;
                stockEntity.Name = (e.Item.FindControl("txtName") as RadTextBox).Text;
                stockEntity.Brand = (e.Item.FindControl("txtBrand") as RadTextBox).Text;
                stockEntity.PromotionalNote = (e.Item.FindControl("txtNote") as RadTextBox).Text;
                stockEntity.UnitStock = (e.Item.FindControl("txtUnitySale") as RadTextBox).Text;
                stockEntity.UnitStockByBox = (e.Item.FindControl("txtUnityBySale") as RadTextBox).Text;

                if (!string.IsNullOrEmpty((e.Item.FindControl("txtMinQuantity") as RadTextBox).Text))
                    stockEntity.MinQuantity = Convert.ToInt32((e.Item.FindControl("txtMinQuantity") as RadTextBox).Text);
                else
                    stockEntity.MinQuantity = 0;

                if (!string.IsNullOrEmpty((e.Item.FindControl("txtReservedQuantity") as RadTextBox).Text))
                    stockEntity.ReservedQuantity = Convert.ToInt32((e.Item.FindControl("txtReservedQuantity") as RadTextBox).Text);
                else
                    stockEntity.ReservedQuantity = 0;

                stockEntity.Description = (e.Item.FindControl("txtDescription") as RadTextBox).Text;
                stockEntity.UnitStock = (e.Item.FindControl("txtUnitySale") as RadTextBox).Text;
                
                stockEntity.StockID = GPSTrackingDBV2Custom.Data.DataRepository.StockProvider.GetNextID(companyId);
                stockEntity.CompanyID = companyId;
                
                stockEntity.LastTick = tick;

                stockEntity.StockCategoryID = getStockCategoryIdSelected();

                if (stockEntity.StockCategoryID == -1)
                {
                    ShowWarningMessage("Debe seleccionar una categoría para el registro del producto.");
                    return;
                }
                else {
                    stockCategoryEntity = new EntityFrameworkManager.FalconSystemProvider().StockCategories.First(x => x.StockCategoryID == stockEntity.StockCategoryID);
                    if (stockCategoryEntity.ParentStockCategoryID == null) {
                        ShowWarningMessage("No se puede asignar productos a la categoría padre, debe seleccionar una categoría de nivel 2, para la correcta visualización de información en la Tablet");
                        return;
                    }
                }                

                stockEntity.StockCategoryID = getStockCategoryIdSelected();

                #endregion

                #region Upload Image
                RadAsyncUpload radUploadImageUrl = e.Item.FindControl("RadAsyncUploadImage") as RadAsyncUpload;
                if (radUploadImageUrl.UploadedFiles.Count > 0)
                {
                    path = GetPathStockImageToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }

                    stockEntity.ImageUrl = radUploadImageUrl.UploadedFiles[0].FileName;
                    
                    radUploadImageUrl.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockImage(stockEntity.ImageUrl)));

                    /*int StockImageWidthMaxSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["StockImageWidthMaxSize"]);

                    //Validate and Resize Image
                    byte[] bytes = new byte[radUploadImageUrl.UploadedFiles[0].ContentLength];
                    radUploadImageUrl.UploadedFiles[0].InputStream.Read(bytes, 0, Convert.ToInt32(radUploadImageUrl.UploadedFiles[0].ContentLength));
                    MemoryStream ms = new MemoryStream(bytes);
                    var image = System.Drawing.Image.FromStream(ms);

                    if (image.Width > StockImageWidthMaxSize)
                    {
                        var newImage = ResizeImageFixedWidth(image, StockImageWidthMaxSize);
                        newImage.Save(Server.MapPath(GetPathStockImage(stockEntity.ImageUrl)));
                    }
                    else
                    {
                        radUploadImageUrl.UploadedFiles[0].InputStream.Flush();
                        radUploadImageUrl.UploadedFiles[0].InputStream.Close();
                        radUploadImageUrl.UploadedFiles[0].InputStream.Dispose();
                        radUploadImageUrl.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockImage(stockEntity.ImageUrl)));
                    }*/

                }
                else
                {
                    ShowWarningMessage("Debe seleccionar una imagen para el registro del producto.");
                    return;
                }

                #endregion

                #region Upload PDF
                
                RadAsyncUpload radUpload = e.Item.FindControl("RadAsyncUploadPDF") as RadAsyncUpload;
                if (radUpload.UploadedFiles.Count > 0)
                {
                    path = GetPathStockPdfToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }

                    stockEntity.PDFDetailUrl = radUpload.UploadedFiles[0].FileName;
                    radUpload.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockPdf(stockEntity.PDFDetailUrl)));
                }
                else
                    stockEntity.PDFDetailUrl = string.Empty;

                #endregion

                #region Upload Video
                                
                stockEntity.VideoUrl = "";
                stockEntity.VideoThumbnailUrl = "";              
                RadAsyncUpload radUploadVideo = e.Item.FindControl("RadAsyncUploadVideo") as RadAsyncUpload;
                if (radUploadVideo.UploadedFiles.Count > 0)
                {
                    path = GetPathStockVideoToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }

                    stockEntity.VideoUrl = radUploadVideo.UploadedFiles[0].FileName;
                    radUploadVideo.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockVideo(stockEntity.VideoUrl)));

                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                    stockEntity.VideoThumbnailUrl = stockEntity.VideoUrl.Replace(radUploadVideo.UploadedFiles[0].GetExtension(), "_thumbnail.jpg");
                    ffMpeg.GetVideoThumbnail(Server.MapPath(GetPathStockVideo(stockEntity.VideoUrl)), Server.MapPath(GetPathStockVideo(stockEntity.VideoThumbnailUrl)), 9);

                }
                else
                {

                    if (!string.IsNullOrEmpty(radUploadVideo.ToolTip))
                    {
                        stockEntity.VideoUrl = radUploadVideo.ToolTip;
                    }
                    else
                        stockEntity.VideoUrl = string.Empty;
                }

                #endregion                

                #region Log

                #region Stock Log

                stockLogEntity.CompanyID = stockEntity.CompanyID;
                stockLogEntity.StockID = stockEntity.StockID;
                stockLogEntity.StockCategoryID = stockEntity.StockCategoryID;

                stockLogEntity.TransactionDate = dateTransaction;
                stockLogEntity.Tick = tick;
                stockLogEntity.SyncTransaction = "I";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                stockLogEntity.TypeUserTransaction = typeUserTransaction;
                stockLogEntity.CompanyIDTransaction = stockEntity.CompanyID;
                stockLogEntity.UsernameTransaction = usernameTransaction;

                stockLogEntity.StockCode = stockEntity.StockCode;
                stockLogEntity.StockBarCode = stockEntity.StockBarCode;
                stockLogEntity.Name = stockEntity.Name;
                stockLogEntity.Description = stockEntity.Description;
                stockLogEntity.PromotionalNote = stockEntity.PromotionalNote;
                stockLogEntity.Brand = stockEntity.Brand;
                stockLogEntity.UnitStock = stockEntity.UnitStock;
                stockLogEntity.UnitStockByBox = stockEntity.UnitStockByBox;
                stockLogEntity.Quantity = stockEntity.Quantity;
                stockLogEntity.MinQuantity = stockEntity.MinQuantity;
                stockLogEntity.Price = stockEntity.Price;
                stockLogEntity.ImageUrl = stockEntity.ImageUrl;
                stockLogEntity.PDFDetailUrl = stockEntity.PDFDetailUrl;
                stockLogEntity.ReservedQuantity = stockEntity.ReservedQuantity;
                stockLogEntity.VideoUrl = stockEntity.VideoUrl;
                stockLogEntity.VideoThumbnailUrl = stockEntity.VideoThumbnailUrl;

                using (var transaction = new TransactionScope(
                                                    TransactionScopeOption.RequiresNew,
                                                    new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
                {
                    using (var dbContext = new EntityFrameworkManager.FalconSystemProvider())
                    {
                        try
                        {
                            dbContext.Stocks.Add(stockEntity);
                            dbContext.StockLogs.Add(stockLogEntity);

                            dbContext.SaveChanges();
                            transaction.Complete();
                        }
                        catch (Exception ex) { 
                            throw new Exception(ex.Message,ex.InnerException);
                        }
                        finally {
                            transaction.Dispose();
                            dbContext.Dispose();
                        }
                        
                    }

                }

                #endregion
                
                #endregion

                #region Upload Aditional Images

                RadAsyncUpload radUploadAditionalImages = e.Item.FindControl("RadAsyncUploadAditionalImages") as RadAsyncUpload;
                if (radUploadAditionalImages.UploadedFiles.Count > 0)
                {

                    path = GetPathStockImageToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }

                    for (int i = 0; i < radUploadAditionalImages.UploadedFiles.Count; i++)
                    {

                        GPSTrackingDBV2.Entities.StockByAditionalImages stockByAditionalImagesEntity = new GPSTrackingDBV2.Entities.StockByAditionalImages();
                        GPSTrackingDBV2.Entities.StockByAditionalImagesLog stockByAditionalImagesLogEntity = new GPSTrackingDBV2.Entities.StockByAditionalImagesLog();

                        stockByAditionalImagesEntity.CompanyId = companyId;
                        stockByAditionalImagesEntity.StockId = stockEntity.StockID;
                        stockByAditionalImagesEntity.NumImage = GPSTrackingDBV2Custom.Data.DataRepository.StockByAditionalImagesProvider.GetNextID(stockByAditionalImagesEntity.CompanyId, stockByAditionalImagesEntity.StockId);
                        stockByAditionalImagesEntity.LastTick = tick;


                        stockByAditionalImagesEntity.ImageUrl = radUploadAditionalImages.UploadedFiles[i].FileName;

                        radUploadAditionalImages.UploadedFiles[i].SaveAs(Server.MapPath(GetPathStockImage(stockByAditionalImagesEntity.ImageUrl)));

                        #region Aditional Images Log
                        GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesProvider.Insert(stockByAditionalImagesEntity);

                        stockByAditionalImagesLogEntity.CompanyId = stockByAditionalImagesEntity.CompanyId;
                        stockByAditionalImagesLogEntity.StockId = stockByAditionalImagesEntity.StockId;
                        stockByAditionalImagesLogEntity.NumImage = stockByAditionalImagesEntity.NumImage;

                        stockByAditionalImagesLogEntity.TransactionDate = dateTransaction;
                        stockByAditionalImagesLogEntity.Tick = tick;
                        stockByAditionalImagesLogEntity.SyncTransaction = "I";

                        if (getSessionManager().IsUser)
                        {
                            typeUserTransaction = "U";
                            usernameTransaction = getSessionManager().Username;
                        }
                        if (getSessionManager().IsAdmin)
                        {
                            typeUserTransaction = "A";
                            usernameTransaction = getSessionManager().AdminUsername;
                        }
                        if (getSessionManager().IsMaster)
                        {
                            typeUserTransaction = "M";
                            usernameTransaction = getSessionManager().MasterUsername;
                        }

                        stockByAditionalImagesLogEntity.TypeUserTransaction = typeUserTransaction;
                        stockByAditionalImagesLogEntity.CompanyIdTransaction = companyId;
                        stockByAditionalImagesLogEntity.UsernameTransaction = usernameTransaction;

                        stockByAditionalImagesLogEntity.ImageUrl = stockByAditionalImagesEntity.ImageUrl;

                        GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesLogProvider.Insert(stockByAditionalImagesLogEntity);

                        #endregion

                    }


                }

                #endregion

                #region Refresh All

                GetStocksByCategories(stockEntity.StockCategoryID);
                ResizeGrid();

                #endregion
            }
            catch (Exception ex)
            {
                TraceLoggerManager.TraceLogger.Error("StockByCategories.aspx", ex);

                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede insertar la información.");
            }
        }

        protected void GetStockCategoriesByParent(int? parentStockCategoryId)
        {
            StocksGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.StockCategoriesProvider.GetByParentStockCategoryId(getSessionManager().CompanyIDSelectedComboBox, parentStockCategoryId);
            StocksGrid.DataBind();
            ResizeGrid();
        }

        protected void StocksGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            string imageUrlToDelete = String.Empty;
            string pdfDetailUrlToDelete = String.Empty;
            string videoUrlToDelete = String.Empty;
            string videoThumbnailUrlToDelete = String.Empty;

            try
            {
                #region Stock Entity Recollect

                EntityFrameworkManager.Stock stockEntity;
                EntityFrameworkManager.StockLog stockLogEntity = new EntityFrameworkManager.StockLog();

                DateTime dateTransaction = DateTime.Now;
                Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
                string typeUserTransaction = "";
                string usernameTransaction = "";
                int companyId = getSessionManager().CompanyIDSelectedComboBox;
                string path;

                //Extract info
                stockEntity = new EntityFrameworkManager.Stock();
                stockEntity.StockID = Convert.ToInt32((e.Item.FindControl("txtStockID") as RadTextBox).Text);
                stockEntity.StockCode = (e.Item.FindControl("txtStockCode") as RadTextBox).Text;
                stockEntity.StockBarCode = (e.Item.FindControl("txtBarCode") as RadTextBox).Text;
                stockEntity.Name = (e.Item.FindControl("txtName") as RadTextBox).Text;
                stockEntity.Brand = (e.Item.FindControl("txtBrand") as RadTextBox).Text;
                stockEntity.PromotionalNote = (e.Item.FindControl("txtNote") as RadTextBox).Text;
                stockEntity.UnitStock = (e.Item.FindControl("txtUnitySale") as RadTextBox).Text;
                stockEntity.UnitStockByBox = (e.Item.FindControl("txtUnityBySale") as RadTextBox).Text;
                stockEntity.Description = (e.Item.FindControl("txtDescription") as RadTextBox).Text;
                stockEntity.UnitStock = (e.Item.FindControl("txtUnitySale") as RadTextBox).Text;
                stockEntity.MinQuantity = Convert.ToInt32((e.Item.FindControl("txtMinQuantity") as RadTextBox).Text);
                stockEntity.ReservedQuantity = Convert.ToInt32((e.Item.FindControl("txtReservedQuantity") as RadTextBox).Text);
                stockEntity.StockCategoryID = Convert.ToInt32((e.Item.FindControl("txtStockCategoryID") as RadTextBox).Text);                

                
                stockEntity.CompanyID = getSessionManager().CompanyIDSelectedComboBox;
                stockEntity.LastTick = tick;

                #endregion

                #region Upload Image
                RadAsyncUpload radUploadImageUrl = e.Item.FindControl("RadAsyncUploadImage") as RadAsyncUpload;

                if (radUploadImageUrl.UploadedFiles.Count > 0)
                {
                    stockEntity.ImageUrl = radUploadImageUrl.UploadedFiles[0].FileName;
                    if (radUploadImageUrl.ToolTip != stockEntity.ImageUrl) imageUrlToDelete = radUploadImageUrl.ToolTip;

                    radUploadImageUrl.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockImage(stockEntity.ImageUrl)));

                    /*int StockImageWidthMaxSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["StockImageWidthMaxSize"]);

                    //Validate and Resize Image
                    byte[] bytes = new byte[radUploadImageUrl.UploadedFiles[0].ContentLength];
                    radUploadImageUrl.UploadedFiles[0].InputStream.Read(bytes, 0, Convert.ToInt32(radUploadImageUrl.UploadedFiles[0].ContentLength));
                    MemoryStream ms = new MemoryStream(bytes);
                    var image = System.Drawing.Image.FromStream(ms);

                    if (image.Width > StockImageWidthMaxSize)
                    {
                        using (Bitmap tempImage = new Bitmap(image))
                        {
                            var newImage = ResizeImageFixedWidth(image, StockImageWidthMaxSize);
                            newImage.Save(Server.MapPath(GetPathStockImage(stockEntity.ImageUrl)));
                        }
                    }
                    else
                    {
                        radUploadImageUrl.UploadedFiles[0].InputStream.Flush();
                        radUploadImageUrl.UploadedFiles[0].InputStream.Close();
                        radUploadImageUrl.UploadedFiles[0].InputStream.Dispose();
                        radUploadImageUrl.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockImage(stockEntity.ImageUrl)));
                    }*/
                    
                }
                else
                {
                    stockEntity.ImageUrl = radUploadImageUrl.ToolTip;
                }

                #endregion

                #region Upload PDF

                RadAsyncUpload radUpload = e.Item.FindControl("RadAsyncUploadPDF") as RadAsyncUpload;
                if (radUpload.UploadedFiles.Count > 0)                
                {
                    path = GetPathStockPdfToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }


                    stockEntity.PDFDetailUrl = radUpload.UploadedFiles[0].FileName;
                    if (radUpload.ToolTip != stockEntity.PDFDetailUrl) pdfDetailUrlToDelete = radUpload.ToolTip;
                    radUpload.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockPdf(stockEntity.PDFDetailUrl)));
                }
                else
                {
                    stockEntity.PDFDetailUrl = radUpload.ToolTip;
                }

                #endregion

                #region Upload Video

                RadAsyncUpload radVideoUpload = e.Item.FindControl("RadAsyncUploadVideo") as RadAsyncUpload;
                if (radVideoUpload.UploadedFiles.Count > 0)
                {
                    path = GetPathStockVideoToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }


                    stockEntity.VideoUrl = radVideoUpload.UploadedFiles[0].FileName;
                    if (radVideoUpload.ToolTip != stockEntity.VideoUrl)
                    {
                        videoUrlToDelete = radVideoUpload.ToolTip;
                        videoThumbnailUrlToDelete = System.IO.Path.GetFileNameWithoutExtension(radVideoUpload.ToolTip) + "_thumbnail.jpg";
                    }
                    radVideoUpload.UploadedFiles[0].SaveAs(Server.MapPath(GetPathStockVideo(stockEntity.VideoUrl)));

                    var ffMpeg = new NReco.VideoConverter.FFMpegConverter();

                    stockEntity.VideoThumbnailUrl = System.IO.Path.GetFileNameWithoutExtension(stockEntity.VideoUrl) + "_thumbnail.jpg";
                    ffMpeg.GetVideoThumbnail(Server.MapPath(GetPathStockVideo(stockEntity.VideoUrl)), Server.MapPath(GetPathStockVideo(stockEntity.VideoThumbnailUrl)), 9);                  
                    
                }
                else
                {
                    
                    
                    if (!string.IsNullOrEmpty(radVideoUpload.ToolTip))
                    {
                        stockEntity.VideoUrl = radVideoUpload.ToolTip;
                        if (radVideoUpload.ToolTip != stockEntity.VideoUrl)
                        {
                            videoThumbnailUrlToDelete = System.IO.Path.GetFileNameWithoutExtension(radVideoUpload.ToolTip) + "_thumbnail.jpg";
                            videoUrlToDelete = radVideoUpload.ToolTip;
                            stockEntity.VideoThumbnailUrl = "";
                        }
                        else
                            stockEntity.VideoUrl = radVideoUpload.ToolTip;
                    }
                    else
                        stockEntity.VideoUrl = radVideoUpload.ToolTip;
                }

                #endregion




                #region Log

                stockLogEntity.CompanyID = stockEntity.CompanyID;
                stockLogEntity.StockID = stockEntity.StockID;
                stockLogEntity.StockCategoryID = stockEntity.StockCategoryID;

                stockLogEntity.TransactionDate = dateTransaction;
                stockLogEntity.Tick = tick;
                stockLogEntity.SyncTransaction = "U";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                stockLogEntity.TypeUserTransaction = typeUserTransaction;
                stockLogEntity.CompanyIDTransaction = stockEntity.CompanyID;
                stockLogEntity.UsernameTransaction = usernameTransaction;

                stockLogEntity.StockCode = stockEntity.StockCode;
                stockLogEntity.StockBarCode = stockEntity.StockBarCode;
                stockLogEntity.Name = stockEntity.Name;
                stockLogEntity.Description = stockEntity.Description;
                stockLogEntity.PromotionalNote = stockEntity.PromotionalNote;
                stockLogEntity.Brand = stockEntity.Brand;
                stockLogEntity.UnitStock = stockEntity.UnitStock;
                stockLogEntity.UnitStockByBox = stockEntity.UnitStockByBox;
                stockLogEntity.Quantity = stockEntity.Quantity;
                stockLogEntity.MinQuantity = stockEntity.MinQuantity;
                stockLogEntity.Price = stockEntity.Price;
                stockLogEntity.ImageUrl = stockEntity.ImageUrl;
                stockLogEntity.PDFDetailUrl = stockEntity.PDFDetailUrl;
                stockLogEntity.ReservedQuantity = stockEntity.ReservedQuantity;

                stockLogEntity.VideoUrl = stockEntity.VideoUrl;
                stockLogEntity.VideoThumbnailUrl = stockEntity.VideoThumbnailUrl;

                using (var transaction = new TransactionScope(
                                                    TransactionScopeOption.RequiresNew,
                                                    new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
                {
                    using (var dbContext = new EntityFrameworkManager.FalconSystemProvider())
                    {
                        try
                        {
                            dbContext.Stocks.Attach(stockEntity);
                            dbContext.Entry(stockEntity).State = EntityState.Modified;

                            dbContext.StockLogs.Add(stockLogEntity);

                            dbContext.SaveChanges();
                            transaction.Complete();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(ex.Message, ex.InnerException);
                        }
                        finally
                        {
                            transaction.Dispose();
                            dbContext.Dispose();
                        }

                    }

                }

                #endregion

                #region Delete images

                /*if (!String.IsNullOrEmpty(imageUrlToDelete))
                    System.IO.File.Delete(Server.MapPath(GetPathStockImage(imageUrlToDelete)));

                if (!String.IsNullOrEmpty(pdfDetailUrlToDelete))
                    System.IO.File.Delete(Server.MapPath(GetPathStockPdf(pdfDetailUrlToDelete)));

                if (!String.IsNullOrEmpty(videoUrlToDelete))
                {
                    System.IO.File.Delete(Server.MapPath(GetPathStockVideo(videoUrlToDelete)));
                    if (!String.IsNullOrEmpty(videoThumbnailUrlToDelete))
                        System.IO.File.Delete(Server.MapPath(GetPathStockVideo(videoThumbnailUrlToDelete)));
                }*/

                #endregion

                GetStocksByCategories(stockEntity.StockCategoryID);
                ResizeGrid();
            }
            catch (Exception ex)
            {
                TraceLoggerManager.TraceLogger.Error("StockByCategories.aspx", ex);

                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede modificar la información.");
            }
        }

        protected void StocksGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                EntityFrameworkManager.Stock stockEntity;
                EntityFrameworkManager.StockLog stockLogEntity = new EntityFrameworkManager.StockLog();

                DateTime dateTransaction = DateTime.Now;
                Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
                string typeUserTransaction = "";
                string usernameTransaction = "";


                stockEntity = new EntityFrameworkManager.Stock();

                Telerik.Web.UI.GridEditableItem item = e.Item as Telerik.Web.UI.GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                int companyID = Convert.ToInt32(Entity["CompanyId"].ToString());
                int stockID = Convert.ToInt32(Entity["StockId"].ToString());

                stockEntity = new EntityFrameworkManager.FalconSystemProvider().Stocks.First(x => x.CompanyID == companyID && x.StockID == stockID);

                if (stockEntity != null)
                {
                    stockEntity.LastTick = tick;

                    stockLogEntity.CompanyID = stockEntity.CompanyID;
                    stockLogEntity.StockID = stockEntity.StockID;
                    stockLogEntity.StockCategoryID = stockEntity.StockCategoryID;

                    stockLogEntity.TransactionDate = dateTransaction;
                    stockLogEntity.Tick = tick;
                    stockLogEntity.SyncTransaction = "D";

                    if (getSessionManager().IsUser)
                    {
                        typeUserTransaction = "U";
                        usernameTransaction = getSessionManager().Username;
                    }
                    if (getSessionManager().IsAdmin)
                    {
                        typeUserTransaction = "A";
                        usernameTransaction = getSessionManager().AdminUsername;
                    }
                    if (getSessionManager().IsMaster)
                    {
                        typeUserTransaction = "M";
                        usernameTransaction = getSessionManager().MasterUsername;
                    }

                    stockLogEntity.TypeUserTransaction = typeUserTransaction;
                    stockLogEntity.CompanyIDTransaction = stockEntity.CompanyID;
                    stockLogEntity.UsernameTransaction = usernameTransaction;

                    stockLogEntity.StockCode = stockEntity.StockCode;
                    stockLogEntity.StockBarCode = stockEntity.StockBarCode;
                    stockLogEntity.Name = stockEntity.Name;
                    stockLogEntity.Description = stockEntity.Description;
                    stockLogEntity.PromotionalNote = stockEntity.PromotionalNote;
                    stockLogEntity.Brand = stockEntity.Brand;
                    stockLogEntity.UnitStock = stockEntity.UnitStock;
                    stockLogEntity.UnitStockByBox = stockEntity.UnitStockByBox;
                    stockLogEntity.Quantity = stockEntity.Quantity;
                    stockLogEntity.MinQuantity = stockEntity.MinQuantity;
                    stockLogEntity.Price = stockEntity.Price;
                    stockLogEntity.ImageUrl = stockEntity.ImageUrl;
                    stockLogEntity.PDFDetailUrl = stockEntity.PDFDetailUrl;
                    stockLogEntity.ReservedQuantity = stockEntity.ReservedQuantity;

                    stockLogEntity.VideoThumbnailUrl = stockEntity.VideoThumbnailUrl;
                    stockLogEntity.VideoUrl = stockEntity.VideoUrl;

                    using (var transaction = new TransactionScope(
                                                    TransactionScopeOption.RequiresNew,
                                                    new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
                    {
                        using (var dbContext = new EntityFrameworkManager.FalconSystemProvider())
                        {
                            try
                            {
                                dbContext.Stocks.Attach(stockEntity);
                                dbContext.Entry(stockEntity).State = EntityState.Deleted;

                                dbContext.StockLogs.Add(stockLogEntity);

                                dbContext.SaveChanges();
                                transaction.Complete();
                            }
                            catch (Exception ex)
                            {
                                throw new Exception(ex.Message, ex.InnerException);
                            }
                            finally
                            {
                                transaction.Dispose();
                                dbContext.Dispose();
                            }

                        }

                    }

                    if (!String.IsNullOrEmpty(stockLogEntity.ImageUrl))
                        System.IO.File.Delete(Server.MapPath(GetPathStockImage(stockLogEntity.ImageUrl)));

                    if (!String.IsNullOrEmpty(stockLogEntity.PDFDetailUrl))
                        System.IO.File.Delete(Server.MapPath(GetPathStockPdf(stockLogEntity.PDFDetailUrl)));

                    if (!String.IsNullOrEmpty(stockLogEntity.VideoUrl))
                        System.IO.File.Delete(Server.MapPath(GetPathStockVideo(stockLogEntity.VideoUrl)));

                    if (!String.IsNullOrEmpty(stockLogEntity.VideoThumbnailUrl))
                        System.IO.File.Delete(Server.MapPath(GetPathStockVideo(stockLogEntity.VideoThumbnailUrl)));

                    GetStocksByCategories(stockEntity.StockCategoryID);
                    ResizeGrid();

                }
                else {
                    ShowErrorMessage("No se puede eliminar la información. Porque no se logró identificar el registro a eliminar");
                }

            }
            catch (Exception ex)
            {
                TraceLoggerManager.TraceLogger.Error("StockByCategories.aspx", ex);

                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede eliminar la información.");
            }
        }

        protected void StocksGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case RadGrid.InitInsertCommandName:
                    Telerik.Web.UI.RadTreeView treeView;
                    
                    if (StockCategoriesGridTree.Items.Count > 0)
                    {
                        treeView = StockCategoriesGridTree.Items[0].FindControl("StockCategoriesGridTreeView") as Telerik.Web.UI.RadTreeView;
                        if (treeView.SelectedNode == null)
                        {
                            ShowWarningMessage("Debe seleccionar una categoría para el registro del producto.");
                            e.Canceled = true;            
                        }
                        else
                        {
                            if (treeView.SelectedNode.Nodes.Count > 0)
                            {
                                ShowWarningMessage("Debe seleccionar una categoría que no tenga subcategorias asociadas para el registro del producto.");
                                e.Canceled = true;
                            }
                        }
                    }
                    break;
                case "AddAditionalImage":

                    if (getStockIdSelected() == -1)
                    {
                        ShowWarningMessage("Debe seleccionar un producto para el registro de las imágenes adicionales.");
                        e.Canceled = true;
                    }
                    break;
            }

            ResizeGrid();
        }

        protected void StocksGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            //setSessionManager(getStockIdSelected());
            getStocksAditionalImagesByStockId();
            StocksAditionalImagesGrid.DataBind();
            ResizeGrid();
        }

        protected int getStockIdSelected()
        {
            try
            {
                return Convert.ToInt32(StocksGrid.Items[StocksGrid.SelectedItems[0].ItemIndex]["StockId"].Text);
            }
            catch { }
            return -1;
        }

        protected void StocksAditionalImagesGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            getStocksAditionalImagesByStockId();
        }

        protected void getStocksAditionalImagesByStockId()
        {
            StocksAditionalImagesGrid.DataSource = GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesProvider.GetByCompanyIdStockId(getSessionManager().CompanyIDSelectedComboBox, getStockIdSelected());
        }

        protected void StocksAditionalImagesGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {           
            DateTime dateTransaction = DateTime.Now;
            Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
            string typeUserTransaction = "";
            string usernameTransaction = "";
            int companyId = getSessionManager().CompanyIDSelectedComboBox;

            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

            if (getStockIdSelected() == -1)
            {
                ShowErrorMessage("Debe seleccionar un producto para registrar las imágenes adicionales.");
                return;
            }


            try
            {
               
                RadAsyncUpload radUpload = e.Item.FindControl("RadAsyncUploadAditionalImages") as RadAsyncUpload;                
                if (radUpload.UploadedFiles.Count > 0)
                {                    
                    String path = GetPathStockImageToCreate();

                    if (!System.IO.Directory.Exists(Server.MapPath(path)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));

                        //Set Write Mode
                        System.Security.AccessControl.DirectorySecurity directorySecurity = System.IO.Directory.GetAccessControl(Server.MapPath(path));
                        directorySecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                        System.IO.Directory.SetAccessControl(Server.MapPath(path), directorySecurity);

                    }

                    

                    for (int i = 0; i < radUpload.UploadedFiles.Count; i++)
                    {
                        tm.BeginTransaction();

                        GPSTrackingDBV2.Entities.StockByAditionalImages stockByAditionalImagesEntity = new GPSTrackingDBV2.Entities.StockByAditionalImages();
                        GPSTrackingDBV2.Entities.StockByAditionalImagesLog stockByAditionalImagesLogEntity = new GPSTrackingDBV2.Entities.StockByAditionalImagesLog();

                        stockByAditionalImagesEntity.CompanyId = companyId;
                        stockByAditionalImagesEntity.StockId = getStockIdSelected();
                        stockByAditionalImagesEntity.NumImage = GPSTrackingDBV2Custom.Data.DataRepository.StockByAditionalImagesProvider.GetNextID(stockByAditionalImagesEntity.CompanyId, stockByAditionalImagesEntity.StockId);
                        stockByAditionalImagesEntity.LastTick = tick;

                        stockByAditionalImagesEntity.ImageUrl = radUpload.UploadedFiles[i].FileName;

                        radUpload.UploadedFiles[i].SaveAs(Server.MapPath(GetPathStockImage(stockByAditionalImagesEntity.ImageUrl)));

                        #region Log

                        GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesProvider.Insert(tm, stockByAditionalImagesEntity);

                        stockByAditionalImagesLogEntity.CompanyId = stockByAditionalImagesEntity.CompanyId;
                        stockByAditionalImagesLogEntity.StockId = stockByAditionalImagesEntity.StockId;
                        stockByAditionalImagesLogEntity.NumImage = stockByAditionalImagesEntity.NumImage;

                        stockByAditionalImagesLogEntity.TransactionDate = dateTransaction;
                        stockByAditionalImagesLogEntity.Tick = tick;
                        stockByAditionalImagesLogEntity.SyncTransaction = "I";

                        if (getSessionManager().IsUser)
                        {
                            typeUserTransaction = "U";
                            usernameTransaction = getSessionManager().Username;
                        }
                        if (getSessionManager().IsAdmin)
                        {
                            typeUserTransaction = "A";
                            usernameTransaction = getSessionManager().AdminUsername;
                        }
                        if (getSessionManager().IsMaster)
                        {
                            typeUserTransaction = "M";
                            usernameTransaction = getSessionManager().MasterUsername;
                        }

                        stockByAditionalImagesLogEntity.TypeUserTransaction = typeUserTransaction;
                        stockByAditionalImagesLogEntity.CompanyIdTransaction = companyId;
                        stockByAditionalImagesLogEntity.UsernameTransaction = usernameTransaction;

                        stockByAditionalImagesLogEntity.ImageUrl = stockByAditionalImagesEntity.ImageUrl;

                        GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesLogProvider.Insert(tm, stockByAditionalImagesLogEntity);

                        #endregion

                        tm.Commit();

                    }

                    
                }
               
               
                getStocksAditionalImagesByStockId();
                StocksAditionalImagesGrid.DataBind();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede insertar la información.");
            }
        }        

        protected void StocksAditionalImagesGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Entities.StockByAditionalImages stockByAditionalImagesEntity = new GPSTrackingDBV2.Entities.StockByAditionalImages();
            GPSTrackingDBV2.Entities.StockByAditionalImagesLog stockByAditionalImagesLogEntity = new GPSTrackingDBV2.Entities.StockByAditionalImagesLog();

            DateTime dateTransaction = DateTime.Now;
            Int64 tick = TickManager.TickManager.GetTick(dateTransaction);
            string typeUserTransaction = "";
            string usernameTransaction = "";
            int companyId = getSessionManager().CompanyIDSelectedComboBox;

            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();

            try
            {
                tm.BeginTransaction();

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                stockByAditionalImagesEntity.CompanyId = companyId;
                stockByAditionalImagesEntity.StockId = int.Parse(Entity["StockId"].ToString());
                stockByAditionalImagesEntity.LastTick = tick;
                stockByAditionalImagesEntity.NumImage = int.Parse(Entity["NumImage"].ToString());

                stockByAditionalImagesEntity.ImageUrl = GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesProvider.GetByCompanyIdStockIdNumImage(stockByAditionalImagesEntity.CompanyId, stockByAditionalImagesEntity.StockId, stockByAditionalImagesEntity.NumImage).ImageUrl;

                GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesProvider.Delete(tm, companyId, stockByAditionalImagesEntity.StockId, stockByAditionalImagesEntity.NumImage);

                stockByAditionalImagesLogEntity.CompanyId = stockByAditionalImagesEntity.CompanyId;
                stockByAditionalImagesLogEntity.StockId = stockByAditionalImagesEntity.StockId;
                stockByAditionalImagesLogEntity.NumImage = stockByAditionalImagesEntity.NumImage;

                stockByAditionalImagesLogEntity.TransactionDate = dateTransaction;
                stockByAditionalImagesLogEntity.Tick = tick;
                stockByAditionalImagesLogEntity.SyncTransaction = "D";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                stockByAditionalImagesLogEntity.TypeUserTransaction = typeUserTransaction;
                stockByAditionalImagesLogEntity.CompanyIdTransaction = companyId;
                stockByAditionalImagesLogEntity.UsernameTransaction = usernameTransaction;

                stockByAditionalImagesLogEntity.ImageUrl = stockByAditionalImagesEntity.ImageUrl;

                GPSTrackingDBV2.Data.DataRepository.StockByAditionalImagesLogProvider.Insert(tm, stockByAditionalImagesLogEntity);

                if (!String.IsNullOrEmpty(stockByAditionalImagesEntity.ImageUrl))
                    System.IO.File.Delete(Server.MapPath(GetPathStockImage(stockByAditionalImagesEntity.ImageUrl)));

                tm.Commit();
                getStocksAditionalImagesByStockId();
                StocksAditionalImagesGrid.DataBind();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                ShowErrorMessage("No se puede eliminar la información.");
            }
        }

        public System.Drawing.Image ResizeImageFixedWidth(System.Drawing.Image imgToResize, int width)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = ((float)width / (float)sourceWidth);

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (System.Drawing.Image)b;
        }
                
    }
}